<template>
  <el-dialog v-model="dialogVisible" title="编辑网址">
    <el-form :model="form" label-width="120px">
      <el-form-item label="网址名称">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="URL地址">
        <el-input v-model="form.url" />
      </el-form-item>
      <el-form-item label="所属分类">
        <el-select v-model="form.categoryId" placeholder="请选择分类">
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import categoriesApi from '@/api/categories'

interface Form {
  id?: number | null
  name: string
  url: string
  categoryId?: number | null
}

const props = defineProps<{
  modelValue: boolean
  initialValues: Form
  categories: Array<{ id: number; name: string }>
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', value: Form): void
}>()

const dialogVisible = ref(props.modelValue)
const form = ref<Form>({ ...props.initialValues })

const submitForm = () => {
  emit('submit', form.value)
  dialogVisible.value = false
}

watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    form.value = { ...props.initialValues }
  }
})
</script>